# encoding=utf-8
"""
响应对象业务校验
"""
import json

from scrapy.exceptions import IgnoreRequest

from zc_core.middlewares.validate import BaseValidateMiddleware
from zc_core.util.http_util import retry_request


class BizValidator(BaseValidateMiddleware):

    def validate_item(self, request, response, spider):
        if not response.text:
            return retry_request(request)
        if response.status == 404:
            raise IgnoreRequest('下架[Item]: %s' % request.url)

        return response

    def validate_price(self, request, response, spider):
        sku_id = request.meta.get('skuId')
        rs = json.loads(response.text)
        if not rs or not rs.get('success', False):
            # 重试：响应数据无效
            spider.logger.info('[Price]响应数据无效: [%s][%s]' % (sku_id, request.meta.get('validate_retry_times', 0)))
            return retry_request(request)

        products = rs.get('products', None)
        if not rs.get('products', None) or sku_id not in products:
            # 放弃：商品下架
            raise IgnoreRequest('[Price]商品下架: [%s]' % sku_id)

        sku_prc = products.get(sku_id, None)
        if not sku_prc or 'price' not in sku_prc:
            # 放弃：商品无价格
            raise IgnoreRequest('[Price]商品无价格: [%s]' % sku_id)

        return response
